package sign.service;

import com.sun.org.apache.xpath.internal.operations.Bool;
import mainpak.BitUtils;
import mainpak.Response;
import mainpak.URLRequest;
import org.springframework.stereotype.Service;
import sign.dao.entity.*;
import sign.dao.mapper.SignMapper;
import util.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author GeChen
 * @Description 查询体征数据服务
 * @date 2019/5/8 11:25
 */
@Service
public class SignService {

    @Resource
    private SignMapper signMapper;

    private static final String baseUrl = "http://101.200.128.17:8088/api/getAccess";

    private static final String baseType = "sign";

    private static final String baseIp = "101.200.128.17";

    private static final String basePort = "8088";

    //根据用户ID返回最新的检测数据
    public String getCaptureDataByUserId(int userId) {

        Log.e(this.getClass().getName(), Thread.currentThread().getStackTrace()[1].getMethodName());

        UserDataVO userDataVO = new UserDataVO();
        CaptureDataPO latestBloodPressure = signMapper.getLatestBloodPressureByUserId(userId);
        if (latestBloodPressure != null) {
            userDataVO.setBloodPressureE(latestBloodPressure.getCheckvalue2());
            userDataVO.setBloodPressureS(latestBloodPressure.getCheckvalue1());
        }

        CaptureDataPO latestECG = signMapper.getLatestECGByUserId(userId);
        if (latestECG != null) {
            DecodeList decodeList = new DecodeList(latestECG.getChecktext());
            List<Double> datas = decodeList.String2List();  //String信息解析为list
            double ECG = decodeList.getECG(datas);
            userDataVO.setEcg(ECG);
        }

        CaptureDataPO latestTemperature = signMapper.getLatestTemperatureByUserId(userId);
        if (latestTemperature != null)
            userDataVO.setTemperature(latestTemperature.getCheckvalue1());

        CaptureDataPO latestBloodOxygen = signMapper.getLatestBloodOxygenByUserId(userId);
        if (latestBloodOxygen != null)
            userDataVO.setBloodOxygen(latestBloodOxygen.getCheckvalue1());

        return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "successful", userDataVO);  //errorcode, message, data
    }

    //根据用户的数据查询相关的体征数据及建议
    public String getSignAndAdviceByCaptureData(UserDataVO userDataVO) {

        Log.e(this.getClass().getName(), Thread.currentThread().getStackTrace()[1].getMethodName());

        List<String> signs = new ArrayList<String>();
        String signAndAdvice = "";

        List<ComplexJudgePO> bloodPressureE = signMapper.getComplexJudgePOByData(userDataVO.getBloodPressureE(), 1, "舒张压");
        List<ComplexJudgePO> bloodPressureS = signMapper.getComplexJudgePOByData(userDataVO.getBloodPressureS(), 1, "收缩压");
//        List<ComplexJudgePO> ECG = signMapper.getComplexJudgePOByData(userDataVO.getEcg(), 2, "心电");
        List<ComplexJudgePO> temperature = signMapper.getComplexJudgePOByData(userDataVO.getTemperature(), 3, "体温");
        List<ComplexJudgePO> bloodOxygen = signMapper.getComplexJudgePOByData(userDataVO.getBloodOxygen(), 4, "血氧");
        //key是判断类型的id,value是统计次数
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();

        for (ComplexJudgePO complexJudgePO : bloodPressureE) {
            if (map.containsKey(complexJudgePO.getJudgeTypeId())) {
                Integer value = map.get(complexJudgePO.getJudgeTypeId());
                value++;
                map.put(complexJudgePO.getJudgeTypeId(), value);
            } else map.put(complexJudgePO.getJudgeTypeId(), 1);
        }

        for (ComplexJudgePO complexJudgePO : bloodPressureS) {
            if (map.containsKey(complexJudgePO.getJudgeTypeId())) {
                Integer value = map.get(complexJudgePO.getJudgeTypeId());
                value++;
                map.put(complexJudgePO.getJudgeTypeId(), value);
            } else map.put(complexJudgePO.getJudgeTypeId(), 1);
        }
//        for (ComplexJudgePO complexJudgePO : ECG) {
//            if (map.containsKey(complexJudgePO.getJudgeTypeId())) {
//                Integer value = map.get(complexJudgePO.getJudgeTypeId());
//                value++;
//                map.put(complexJudgePO.getJudgeTypeId(), value);
//            } else map.put(complexJudgePO.getJudgeTypeId(), 1);
//        }
        for (ComplexJudgePO complexJudgePO : temperature) {
            if (map.containsKey(complexJudgePO.getJudgeTypeId())) {
                Integer value = map.get(complexJudgePO.getJudgeTypeId());
                value++;
                map.put(complexJudgePO.getJudgeTypeId(), value);
            } else map.put(complexJudgePO.getJudgeTypeId(), 1);
        }
        for (ComplexJudgePO complexJudgePO : bloodOxygen) {
            if (map.containsKey(complexJudgePO.getJudgeTypeId())) {
                Integer value = map.get(complexJudgePO.getJudgeTypeId());
                value++;
                map.put(complexJudgePO.getJudgeTypeId(), value);
            } else map.put(complexJudgePO.getJudgeTypeId(), 1);
        }
        int maxKey = 0;
        int maxValue = 0;
        Iterator<Integer> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            Integer key = iterator.next();
            Integer value = map.get(key);
            if (value > maxValue) {
                maxValue = value;
                maxKey = key;
            }
        }

        JudgeInfoPO judgeInfoPO = signMapper.getJudgeInfoById(maxKey);
        if (judgeInfoPO == null)
            return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请联系系统管理员", "");
        else
            return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "查询成功", judgeInfoPO.getJudgeInfo());
//        InfoPO bloodPressureE = signMapper.getInfoPOByData(userDataVO.getBloodPressureE(), 1, "舒张压");
//        InfoPO bloodPressureS = signMapper.getInfoPOByData(userDataVO.getBloodPressureS(), 1, "收缩压");
////        signAndAdvice += "舒张压：";
//        if (bloodPressureE != null)
//            signAndAdvice = ("您的舒张压为：" + userDataVO.getBloodPressureE() + "mmHg，" + bloodPressureE.getSignInfo() + bloodPressureE.getAdvice());
//        else signAndAdvice = "暂无相关数据";
//        signs.add(signAndAdvice);
//
////        signAndAdvice = "\n\r收缩压：";
//        if (bloodPressureS != null)
//            signAndAdvice = ("您的收缩压为：" + userDataVO.getBloodPressureS() + "mmHg，" + bloodPressureS.getSignInfo() + bloodPressureS.getAdvice());
//        else signAndAdvice = "暂无相关数据";
//        signs.add(signAndAdvice);
//
//        InfoPO ECG = signMapper.getInfoPOByData(userDataVO.getECG(), 2, "心率");
//
//        if (ECG != null)
//            signAndAdvice = ("您的心率为：" + userDataVO.getECG() + "次/分钟，" + ECG.getSignInfo() + ECG.getAdvice());
//        else signAndAdvice = "暂无相关数据";
//        signs.add(signAndAdvice);
//
//        InfoPO temperature = signMapper.getInfoPOByData(userDataVO.getTemperature(), 3, "体温");
////        signAndAdvice += "\n\r体温：";
//        if (temperature != null)
//            signAndAdvice = ("您的体温为：" + userDataVO.getTemperature() + "℃，" + temperature.getSignInfo() + temperature.getAdvice());
//        else signAndAdvice = "暂无相关数据";
//        signs.add(signAndAdvice);
//
//        InfoPO bloodOxygen = signMapper.getInfoPOByData(userDataVO.getBloodOxygen(), 4, "血氧");
////        signAndAdvice+="\n\r血氧：";
//        if (bloodOxygen != null)
//            signAndAdvice = ("您的血氧为：" + userDataVO.getBloodOxygen() + "%，" + bloodOxygen.getSignInfo() + bloodOxygen.getAdvice());
//        else signAndAdvice = "暂无相关数据";
//        signs.add(signAndAdvice);
    }

    public String getAdvice(AdviceVO adviceVO) {
//        return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请联系系统管理员", "");
        String appId = adviceVO.getAppId();
        String salt = MD5Util.salt;  //"盐值"，用于md5加密
        String inputSign = adviceVO.getSign();
        String calSign = MD5Util.md5(appId + salt);  //对 appId+salt 进行md5加密
        //认证错误
        StringBuilder stringBuilder = new StringBuilder(baseUrl);
        stringBuilder.append("?");
        stringBuilder.append("appId=" + appId);
        stringBuilder.append("&");
        stringBuilder.append("type=" + baseType);
        String finalUrl = stringBuilder.toString();
        //使用RestTemplate.getForObject()返回ResponseVO对象
        ResponseVO responseVO = RestConfig.restTemplate().getForObject(finalUrl, ResponseVO.class);
        if (responseVO.getCode() == 400) {
            return ResponseUtil.getResponseString(ErrorCode.APPID_NOT_EXIST, responseVO.getMessage(), "");
        }
        if (responseVO.getCode() == 401) {
            return ResponseUtil.getResponseString(ErrorCode.SERVICE_NOT_AVAILABLE, responseVO.getMessage(), "");
        }
        if (!inputSign.equals(calSign)) {
            return ResponseUtil.getResponseString(ErrorCode.SIGN_ERROR, "认证错误，请仔细校对认证码", "");
        }
        UserDataVO userDataVO = new UserDataVO();
        userDataVO.setBloodOxygen(adviceVO.getBloodOxygen());
        userDataVO.setEcg(adviceVO.getEcg());
        userDataVO.setBloodPressureE(adviceVO.getBloodPressureE());
        userDataVO.setBloodPressureS(adviceVO.getBloodPressureS());
        userDataVO.setTemperature(adviceVO.getTemperature());
        //根据用户体征数据返回建议
        return getSignAndAdviceByCaptureData(userDataVO);
    }

    //cjn - 根据新的用户体征数据查询具体措施
//    public String getAdviceByNewCaptureData(NewUserDataVO userDataVO){
//        //根据各项体征数据查询对应的措施内容
//        List<String> infos = signMapper.getNewCaptureInfoByValue(
//                userDataVO.getTemperature(),
//                userDataVO.getBloodOxygen(),
//                userDataVO.getHeartRate(),
//                userDataVO.getDiastolicPressure(),
//                userDataVO.getSystolicPressure());
//        //数据库里没有此数据
//        if(infos.size() == 0){
//            return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请联系系统管理员", "");
//        }
//        //处理得到的措施infos
//        StringBuilder stringBuilder = new StringBuilder();
//        for(String info: infos){
//            if(info != null){
//                stringBuilder.append(info);
//            }
//        }
//        //计算心肌耗氧量并获取相应的措施
//        double mocValue = userDataVO.getHeartRate() * userDataVO.getSystolicPressure();
//        if(mocValue >= 5401){
//            String mocMeasure = signMapper.getMocMeasure(mocValue);
//            if(mocMeasure != null){
//                stringBuilder.append("心肌耗氧量的情况：" + mocMeasure);
//            }
//        }
//        //stringbuilder转为string
//        String result_info = stringBuilder.toString();
//        if(result_info == null) {
//            return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请联系系统管理员", "");
//        } else{
//            return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "查询成功", result_info);
//        }
//    }

    //cjn -新 -根据用户体征查询具体措施（修改appId认证方式，修改数据库查询数据方式）
    public String getAdviceByNewCaptureData(NewUserDataVO userDataVO){
        //根据各项体征查询对应的data_id
        List<Integer> list1 = signMapper.getDataIdsByCaptureData(userDataVO.getTemperature(), 1, 1);
        List<Integer> list2 = signMapper.getDataIdsByCaptureData(userDataVO.getBloodOxygen(), 2, 1);
        List<Integer> list3 = signMapper.getDataIdsByCaptureData(userDataVO.getHeartRate(), 3, 1);
        List<Integer> list4 = signMapper.getDataIdsByCaptureData(userDataVO.getDiastolicPressure(), 4, 1);
        List<Integer> list5 = signMapper.getDataIdsByCaptureData(userDataVO.getSystolicPressure(), 5, 1);
        if(list1.size() == 0 || list2.size() == 0 || list3.size() == 0 || list4.size() == 0 || list5.size() == 0){
            return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请联系系统管理员", "");
        }

        //根据各项data_id查询对应的infoIds
        List<Integer> infoIds = signMapper.getMeasuresInfoIdsByDataIds(list1, list2, list3, list4, list5);
        if(infoIds == null || infoIds.size() == 0){
            return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请联系系统管理员", "");
        }

        //根据infoIds查询对应的措施
        List<String> infos = signMapper.getMeasuresByMeasuresInfoIds(infoIds);
        if(infos == null || infos.size() == 0){
            return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请联系系统管理员", "");
        }

        //处理得到的措施
        StringBuilder stringBuilder = new StringBuilder();
        for(String info: infos){
            stringBuilder.append(info);
        }

        //计算心肌耗氧量并获取相应的措施
        double mocValue = userDataVO.getHeartRate() * userDataVO.getSystolicPressure();
        if(mocValue >= 5401){
            String mocMeasure = signMapper.getMocMeasure(mocValue);
            if(mocMeasure != null){
                stringBuilder.append("心肌耗氧量的情况：" + mocMeasure);
            }
        }

        //stringbuilder转为string
        String result_info = stringBuilder.toString();
        if(result_info == null) {
            return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请联系系统管理员", "");
        } else{
            return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "查询成功", result_info);
        }
    }

    //cjn - 返回措施
    public String getNewAdvice(NewAdviceVO adviceVO){
//        String appId = adviceVO.getAppId();
//        String salt = MD5Util.salt;  //"盐值"，用于md5加密
//        String inputSign = adviceVO.getSign();
//        String calSign = MD5Util.md5(appId + salt);  //对 appId+salt 进行md5加密
//        //认证错误
//        StringBuilder stringBuilder = new StringBuilder(baseUrl);
//        stringBuilder.append("?");
//        stringBuilder.append("appId=" + appId);
//        stringBuilder.append("&");
//        stringBuilder.append("type=" + baseType);
//        String finalUrl = stringBuilder.toString();
//        //使用RestTemplate.getForObject()返回ResponseVO对象
//        ResponseVO responseVO = RestConfig.restTemplate().getForObject(finalUrl, ResponseVO.class);
//        if (responseVO.getCode() == 400) {
//            return ResponseUtil.getResponseString(ErrorCode.APPID_NOT_EXIST, responseVO.getMessage(), "");
//        }
//        if (responseVO.getCode() == 401) {
//            return ResponseUtil.getResponseString(ErrorCode.SERVICE_NOT_AVAILABLE, responseVO.getMessage(), "");
//        }
//        if (!inputSign.equals(calSign)) {
//            return ResponseUtil.getResponseString(ErrorCode.SIGN_ERROR, "认证错误，请仔细校对认证码", "");
//        }

        //进行服务认证
        String appId = adviceVO.getAppId();
        String inputSign = adviceVO.getSign();
        Response<Boolean> response = new Response<Boolean>();
        response = BitUtils.Access(appId, inputSign, baseType,
                new URLRequest.Builder().setIp(baseIp).setPort(basePort).build());
        if(!response.getData()){
            return response.toString();
        }

        //将得到的输入数据转换为NewUserDataVO类对象
        NewUserDataVO userDataVO = new NewUserDataVO();
        userDataVO.setTemperature(adviceVO.getTemperature());
        userDataVO.setBloodOxygen(adviceVO.getBloodOxygen());
        userDataVO.setHeartRate(adviceVO.getHeartRate());
        userDataVO.setDiastolicPressure(adviceVO.getDiastolicPressure());
        userDataVO.setSystolicPressure(adviceVO.getSystolicPressure());
        //根据输入数据进行措施查询
        return getAdviceByNewCaptureData(userDataVO);
    }

    /*
    2020.12需求：根据体征返回临床判断和医学建议
     */
    //根据用户生命体征获取临床判断和医学建议
    public String getJudgementAndAdvice(IntelligentJudgeUserDataVO userDataVO){
        if(userDataVO == null){
            return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请输入用户体征数据", "");
        }
        //根据各项生命体征查询对应的data_id
        List<Integer> list1 = signMapper.getDataIdsByCaptureData(userDataVO.getTemperature(), 1, 2);
        List<Integer> list2 = signMapper.getDataIdsByCaptureData(userDataVO.getHeartRate(), 3, 2);
        List<Integer> list3 = signMapper.getDataIdsByCaptureData(userDataVO.getRespiratoryRate(), 6, 2);
        List<Integer> list4 = signMapper.getBloodPressureId(userDataVO.getSystolicPressure(), userDataVO.getDiastolicPressure());
//        List<Integer> list5 = signMapper.getDataIdsByCaptureData(userDataVO.getAmbientTemperature(), 7, 2);
        List<Integer> list5 = signMapper.getAmbientTemperatureId(userDataVO.getAmbientTemperature(), 7, 2);
        if(list1.size() == 0 || list2.size() == 0 || list3.size() == 0 || list4.size() == 0 || list5.size() == 0){
            return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请联系系统管理员", "");
        }

        //根据各项data_id查询对应的临床判断和医学建议的id
        List<IntelligentJudgePO> adviceIds = signMapper.getClinicalJudgeAndMedicalAdvice(list1, list2, list3, list4, list5);
        if(adviceIds == null || adviceIds.size() == 0){
            return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请联系系统管理员", "");
        }

        //根据id获取临床判断和医学建议
        List<Integer> clinicalIds = new ArrayList<Integer>();
        List<Integer> medicalIds = new ArrayList<Integer>();
        for(IntelligentJudgePO intelligentJudgePO: adviceIds){
            clinicalIds.add(intelligentJudgePO.getClinicalJudgementId());
            medicalIds.add(intelligentJudgePO.getMedicalAdviceId());
        }
        List<String> clinicalJudgements = signMapper.getClinicalJudgementById(clinicalIds);
        List<String> medicalAdvice = signMapper.getMedicalAdviceById(medicalIds);
        if(clinicalJudgements == null || clinicalJudgements.size() == 0 || medicalAdvice == null || medicalAdvice.size() == 0){
            return ResponseUtil.getResponseString(ErrorCode.INSERT_ERROR, "查询错误，请联系系统管理员", "");
        }

        //整合临床判断和医学建议并返回
        StringBuilder stringBuilder = new StringBuilder();
        for(int i = 0; i < clinicalJudgements.size(); i++){
            stringBuilder.append("临床判断：");
            stringBuilder.append(clinicalJudgements.get(i));
            stringBuilder.append("；医学建议：");
            stringBuilder.append(medicalAdvice.get(i));
        }
        String res = stringBuilder.toString();
        return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "查询成功", res);

    }

    //返回临床判断和医学建议
    public String returnJudgementAndAdvice(IntelligentJudgeVO intelligentJudgeVO){
        //进行服务认证
        String appId = intelligentJudgeVO.getAppId();
        String inputSign = intelligentJudgeVO.getSign();
        Response<Boolean> response = BitUtils.Access(appId, inputSign, baseType,
                new URLRequest.Builder().setIp(baseIp).setPort(basePort).build());
        if(!response.getData()){
            return response.toString();
        }

        //IntelligentJudgeVO类对象转换为IntelligentJudgeUserDataVO
        IntelligentJudgeUserDataVO userDataVO = new IntelligentJudgeUserDataVO();
        userDataVO.setTemperature(intelligentJudgeVO.getTemperature());
        userDataVO.setHeartRate(intelligentJudgeVO.getHeartRate());
        userDataVO.setRespiratoryRate(intelligentJudgeVO.getRespiratoryRate());
        userDataVO.setSystolicPressure(intelligentJudgeVO.getSystolicPressure());
        userDataVO.setDiastolicPressure(intelligentJudgeVO.getDiastolicPressure());
        userDataVO.setAmbientTemperature(intelligentJudgeVO.getAmbientTemperature());

        //返回临床判断和医学建议
        return getJudgementAndAdvice(userDataVO);
    }






}

